package study.springcloud.gateway.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import study.eggs.result.Result;
import study.eggs.result.Results;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
public class DiscoveryController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service")
    public Result echo(@RequestParam String serviceId) {
        List<ServiceInstance> instanceLt = discoveryClient.getInstances(serviceId);
        List<Map<String, Object>> dataLt = Lists.newArrayList();
        for (ServiceInstance instance : instanceLt) {
            Map<String, Object> data = Maps.newHashMap();
            data.put("instanceId", instance.getInstanceId());
            data.put("scheme", instance.getScheme());
            data.put("host", instance.getHost());
            data.put("port", instance.getPort());
            data.put("uri", instance.getUri());
            dataLt.add(data);
        }
        return Results.ok(dataLt);
    }
}
